<template>
  <div class="add-app-dialog">

    <el-dialog
        v-model="dialogVisible"
        :before-close="handleClose"
        :title="title"
        width="500px"
    >

      <el-form
          ref="ruleForm"
          :model="formData"
          :rules="rules"
          class="demo-ruleForm"
          label-width="140px"
      >
        <el-form-item label="终端名称" prop="name">
          <!--                    <el-input v-model="formData.name" placeholder="请输入终端名称"></el-input>-->

          <el-autocomplete
              v-model="formData.name"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入终端名称"
              @blur="nameBlur"
              @select="handleSelect"
          />
        </el-form-item>

        <el-form-item v-if="selectData && selectData.errorStatus">
          <span style="color:red">{{ errMap[selectData.errorStatus] }}</span>
        </el-form-item>

        <el-form-item v-else-if="isRepeat">
          <span style="color:red">终端已添加</span>
        </el-form-item>

        <el-form-item label="所在地区">
          <span>{{ formData.area }}</span>
          <!--                    <el-input v-model="formData.area"></el-input>-->
        </el-form-item>

        <el-form-item v-if="isDeadlin" label="开发期限截止日期" prop="date">
          <date-picker v-model:date="formData.date" placeholder="请选择截止日期" @change="dateChange"/>
        </el-form-item>

        <el-form-item v-if="isDeadlin" label="开发保证金" prop="devEarnestMoney">
          <el-input v-model="formData.devEarnestMoney" placeholder="请输入开发保证金"/>
        </el-form-item>

        <el-form-item label="最低销量">

          <div class="specail-input">
            <el-input v-model="formData.minSale" placeholder="请输入最低销量" @blur="salesBlur"/>
            <el-select v-model="formData.minSaleUnit" placeholder="">
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </div>

        </el-form-item>

        <el-form-item label="销量保证金">

          <el-input v-model="formData.sellEarnestMoney" clearable placeholder="请输入销量保证金" @blur="salesPriceBlur"/>

        </el-form-item>

        <el-form-item label="其他说明">

          <el-input v-model="formData.remark" clearable placeholder="请输入其他说明"/>

        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="addClick">添加并继续</el-button>
          <el-button type="primary" @click="dialogConfirm">添加</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import {crmStore} from '@CRM/store'
import {defineComponent, getCurrentInstance, inject, reactive, ref} from 'vue'

export default defineComponent({
  name: 'AddAppDialog',
  props: {
    planId: {
      type: Number,
      default: 0
    },
    list: {
      type: Array,
      default: []
    },
    title: {
      type: String,
      default: '添加招商终端'
    },
    isDeadlin: {
      type: Boolean,
      default: true
    },
    mode: {
      type: Boolean,
      default: 'plan'
    },
    id: {
      type: Number,
      default: 0,
    }
  },
  setup(props, {emit}) {
    const currentInstance = getCurrentInstance()
    const api = inject('api')

    var isRepeat = ref(false)
    var ruleForm = ref(null)
    var dialogVisible = ref(false)
    var errMap = ref({})
    var selectData = ref({})
    const options = crmStore.getters['dictionary/getDictionary']['sell_num_unit']

    const rules = ref({
      name: [
        {
          required: true,
          message: '请输入终端名称',
          trigger: 'change',
        },
      ],
      devEarnestMoney: [
        {
          required: true,
          message: '请输入开发保证金',
          trigger: 'blur',
        },
      ],
      date: [
        {
          type: 'date',
          required: true,
          message: '请选择结束日期',
          trigger: 'change',
        },
      ],
    })

    var formData = reactive({
      terminalId: '',
      name: '',
      area: '',
      date: '',
      expireTime: '',
      devEarnestMoney: '',
      exploitStr: '',
      minSale: 0,
      minSaleUnit: '',
      sellEarnestMoney: '',
      remark: '',
    })

    const handleClose = () => {
      formData.area = ''
      formData.minSale = ''
      ruleForm.value.resetFields()
      setTimeout(() => {
        ruleForm.value.clearValidate()
        dialogVisible.value = false
      }, 100)
    }

    const addClick = () => {
      if (selectData.value.errorStatus) {
        currentInstance.proxy.customMessage({type: 'error', message: errMap.value[selectData.value.errorStatus]})
        return
      } else if (isRepeat.value) {
        currentInstance.proxy.customMessage({type: 'error', message: '终端已添加'})
        return
      }
      ruleForm.value.validate((val) => {
        if (val) {
          formData.exploitPrice = '¥' + formData.devEarnestMoney
          formData.devEarnestMoney = Number(formData.devEarnestMoney)
          if (formData.sellEarnestMoney) {
            formData.salesStr = '¥' + formData.sellEarnestMoney
            formData.sellEarnestMoney = Number(formData.sellEarnestMoney)
          }

          emit('confirm', {...formData})
          formData.area = ''

          ruleForm.value.resetFields()

          setTimeout(() => {
            ruleForm.value.clearValidate()
          }, 100)
        }
      })
    }

    const dialogConfirm = () => {
      if (selectData.value.errorStatus) {
        currentInstance.proxy.customMessage({type: 'error', message: errMap.value[selectData.value.errorStatus]})
        return
      } else if (isRepeat.value) {
        currentInstance.proxy.customMessage({type: 'error', message: '终端已添加'})
        return
      }
      ruleForm.value.validate((val) => {
        if (val) {
          formData.exploitPrice = '¥' + formData.devEarnestMoney
          formData.devEarnestMoney = Number(formData.devEarnestMoney)
          if (formData.sellEarnestMoney) {
            formData.salesStr = '¥' + formData.sellEarnestMoney
            formData.sellEarnestMoney = Number(formData.sellEarnestMoney)
          }

          emit('confirm', {...formData})
          formData.area = ''

          ruleForm.value.resetFields()

          setTimeout(() => {
            ruleForm.value.clearValidate()
            dialogVisible.value = false
          }, 100)
        }
      })
    }

    const dateChange = () => {
      if (formData.date) {
        formData.expireTime = formData.date
      }// currentInstance.proxy.dateFormat('yyyy-mm-dd HH:MM:SS',formData.date)
    }

    const querySearchAsync = (queryString, cb) => {
      // selectData.value = null
      isRepeat.value = false

      if (!queryString) {
        cb([])
        return
      }
      const data = {
        id: props.id,
        terminalName: queryString,
        ModelType: props.mode == 'plan' ? 1 : 2
      }

      api.common.TERMINAL_CHECK_TERMINAL(data).then(res => {
        if (!res.code) {
          if (res.data.list && res.data.list.terminalList) {
            res.data.list.terminalList.forEach(item => {
              item.value = item.terminal.terminalName
            })
            errMap.value = res.data.list.errMap
            cb(res.data.list.terminalList)
          }
        } else {
          cb([])
        }
      })
    }

    const createFilter = (queryString) => {
      return (restaurant) => {
        return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1
        )
      }
    }

    const openDialog = () => {
      console.log(formData.minSale)
      dialogVisible.value = true
    }

    const handleSelect = (item) => {
      selectData.value = item
      if (props.list.findIndex(a => a.terminalId == item.id) != -1) {
        isRepeat.value = true
      } else {
        isRepeat.value = false
      }

      formData.terminalId = item.terminal.id
      formData.name = item.value
      formData.area = ''
      if (item.terminal.provinceName) {
        formData.area = item.terminal.provinceName
      }
      if (item.terminal.cityName) {
        formData.area = formData.area + '/' + item.terminal.provinceName
      }
      if (item.terminal.areaName) {
        formData.area = formData.area + '/' + item.terminal.areaName
      }
    }

    const nameBlur = () => {
      if (selectData.value) {
        formData.name = selectData.value.value
      }
    }

    const salesBlur = (row) => {
      if (formData.minSale) {
        formData.minSale = Number(formData.minSale)
      } else {
        formData.minSale = 0
      }
    }

    const salesPriceBlur = (row) => {
      if (formData.sellEarnestMoney) {
        formData.salesStr = '¥' + formData.sellEarnestMoney
        formData.sellEarnestMoney = Number(formData.sellEarnestMoney)
      } else {
        formData.salesStr = ''
        formData.sellEarnestMoney = 0
      }
    }

    return {
      ruleForm,
      dialogVisible,
      rules,
      formData,
      options,
      errMap,
      selectData,
      isRepeat,

      handleClose,
      dialogConfirm,
      openDialog,
      querySearchAsync,
      handleSelect,
      dateChange,
      salesBlur,
      salesPriceBlur,
      addClick,
      nameBlur
    }
  }
})
</script>

<style lang="scss">

.add-app-dialog {
  .el-autocomplete {
    width: 100%;
  }

  .el-input {
    width: 100%;
  }

  .specail-input {
    display: flex;

    .el-input__inner {
      border-radius: 5px 0 0 5px;
    }

    .el-select {
      width: 110px;

      .el-input__inner {
        border-radius: 0 5px 5px 0;
        border-left: 0;
      }
    }
  }
}
</style>
